package com.hengyue.system.service.impl;

import com.hengyue.common.utils.StringUtils;
import com.hengyue.security.utils.SecurityUtils;
import com.hengyue.system.domain.entity.SysRole;
import com.hengyue.system.domain.entity.SysUser;
import com.hengyue.system.repository.MenuRepository;
import com.hengyue.system.repository.SysRoleRepository;
import com.hengyue.system.service.ISysPermissionService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
@RequiredArgsConstructor
public class SysPermissionServiceImpl implements ISysPermissionService {

    private final MenuRepository sysMenuService;

    private final SysRoleRepository roleRepository;


    @Override
    public Set<String> getRolePermission(SysUser user) {

        List<SysRole> roles = roleRepository.findRoleKeysByUserId(user.getId());
        Set<String> roleKeys = new HashSet<String>();
        // 管理员拥有所有权限
        if (SecurityUtils.isAdmin(user.getId())) {
            roleKeys.add("admin");
        } else {
            // 遍历用户关联的角色
            for (SysRole role : roles) {
                if (StringUtils.isNotNull(role)) {
                    roleKeys.addAll(Arrays.asList(role.getRoleKey().trim().split(",")));
                }
            }
        }
        return roleKeys;
    }

    @Override
    public Set<String> getMenuPermission(SysUser user) {

        Set<String> perms = new HashSet<String>();
        // 管理员拥有所有权限
        if (SecurityUtils.isAdmin(user.getId())) {
            perms.add("*:*:*");
        } else {
            // 直接通过用户ID获取所有菜单权限
            perms.addAll(sysMenuService.selectMenuPermsByUserId(user.getId()));
        }
        return perms;
    }
}
